<template>
  <el-main>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home/index/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbNameP }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ breadcrumbName }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :model="formInline" class="el-form query-form el-form--label-right el-form--inline">
      <el-form-item label="选择日期">
        <el-date-picker size="small" v-model="formInline.dataValue" type="daterange" align="right" unlink-panels
          range-separator="-" format="yyyy - MM - dd " value-format="yyyy-MM-dd" start-placeholder="开始日期"
          end-placeholder="结束日期" @change="changeDatePicker">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="登录名">
        <el-input size="small" v-model="formInline.UserName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="onSearch" icon="el-icon-search">搜 索</el-button>
        <el-button size="small" type="default" @click="handleAdd" icon="el-icon-plus">添 加</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-tree style="max-height:500px;overflow-y: auto;" :data="allDeptData" :props="defaultProps"
          @node-click="handleNodeClick" class="myTree"></el-tree>
      </el-col>
      <el-col :span="19">
        <el-table :data="tableData" style="margin-top:30px">
          <el-table-column prop="user_name" label="登录名" fixed="left"></el-table-column>
          <el-table-column prop="dept_name" label="所属部门"></el-table-column>
          <!-- :formatter="formatDeptName" -->
          <el-table-column prop="dept_names" label="可查看部门" :formatter="formatDept"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="phone" label="电话"></el-table-column>
          <el-table-column prop="create_dt" label="创建时间"></el-table-column>
          <el-table-column prop="status" label="状态"  :formatter ="formatStatu"></el-table-column>
          <!-- <el-table-column prop="deptType" label="用户类型" :formatter="formatType"></el-table-column> -->
          <el-table-column label="操作" width="250" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="default" @click="handleEdit(scope.$index, scope.row)">编辑
              </el-button>
              <el-button size="mini" type="primary"
                @click="handleDelete(scope.$index, scope.row, 3, '此操作將刪除该数据, 是否继续？', '删除')">删除
              </el-button>
              <el-tooltip placement="bottom" effect="light">
                <div slot="content" class="buttomSty">
                  <el-button size="mini" @click="handleDelete(scope.$index, scope.row, 2,'此操作將冻结该数据, 是否继续？', '冻结')">冻结
                  </el-button><br>
                  <el-button size="mini" @click="handleDelete(scope.$index, scope.row, 1, '此操作將解冻该数据, 是否继续？', '解冻')">解冻
                  </el-button><br>
                  <el-button size="mini" @click="handleRole(scope.$index, scope.row)">角色分配</el-button>
                  <br>
                  <el-button size="mini" @click="handleReset(scope.$index, scope.row)">重置密码
                  </el-button>
                </div>
                <el-button size="mini">更多</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="formInline.page"
      :page-size="formInline.limit" :hide-on-single-page="true" layout="total, prev, pager, next" :total="total">
    </el-pagination>
    <!-- 添加窗口 -->
    <el-dialog title="添 加" :visible.sync="addDialogVisible" width="40%" center custom-class="center_dislog"
      @close="closeForm">
      <el-form ref="addForm" :model="addForm" label-width="100px" :rules="rules">
        <el-form-item label="用户权限等级" prop="PermLevel">
          <el-radio-group v-model="addForm.PermLevel">
            <el-radio :label="0">普通用户</el-radio>
            <el-radio :label="2">普通管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="用户类型" prop="type">
          <el-radio-group v-model="addForm.type">
            <el-radio label="0">后台用户</el-radio>
            <el-radio label="1" v-if="addForm.perm_level==0">承运商</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- 登录名 -->
        <el-form-item label="登录名" prop="UserName">
          <el-input v-model="addForm.UserName" placeholder="请输入"></el-input>
        </el-form-item>
           <!-- <el-form-item label="昵称" prop="nickName">
          <el-input v-model="editForm.nickName" placeholder="请输入"></el-input>
        </el-form-item> -->
        <!-- 部门 -->
        <el-form-item label="所属部门" prop="PlaceDeptId" >
          <el-tree style="max-height:200px;overflow-y: auto;" :data="deptData" @check="handleDeptAddNodeCheck"
            show-checkbox node-key="id" ref="dept_tree" :props="defaultProps" :check-strictly="true"
            class="myDialogTree">
          </el-tree>
        </el-form-item>
        <el-form-item label="可查看部门" prop="VisitDeptIds" >
          <el-tree style="max-height:200px;overflow-y: auto;" :data="deptData" show-checkbox node-key="id"
            ref="dept_add_tree" :props="defaultProps" :check-strictly="true" class="myDialogTree">
          </el-tree>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input type="text" v-model="addForm.phone" autocomplete="off" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="addForm.email" autocomplete="off" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 登录密码 -->
        <el-form-item label="登录密码" prop="password"
          :rules="[{ required: true, message:  '密码不能为空', trigger: 'blur' },{ min: 6, max: 30, message:  '密码长度不少于6位', trigger: 'blur' }]">
          <el-input placeholder="请输入" v-model="addForm.password" show-password></el-input>
        </el-form-item>
        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="password2">
          <el-input placeholder="请输入" v-model="addForm.password2" show-password></el-input>
        </el-form-item>
        <!-- <el-form-item label="所属承运商" prop="carrier_id" v-if="addForm.type==1">
          <el-autocomplete v-model="carrier_name" :fetch-suggestions="queryCarrier" placeholder="请输入"
            @select="handleSelect"></el-autocomplete>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeForm('close')">取 消</el-button>
        <el-button type="primary" :disabled="addDisabled" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="编 辑" :visible.sync="editDialogVisible" width="40%" center custom-class="center_dislog">
      <el-form ref="editForm" :model="editForm" label-width="100px">
        <el-form-item label="登录名" prop="UserName">
          <el-input v-model="editForm.UserName" placeholder="请输入"></el-input>
        </el-form-item>
           <!-- <el-form-item label="昵称" prop="nickName">
          <el-input v-model="editForm.nickName" placeholder="请输入"></el-input>
        </el-form-item> -->
        <!-- 部门 -->
        <el-form-item label="所属部门" prop="PlaceDeptId" >
          <el-tree style="max-height:200px;overflow-y: auto;" :data="deptData" @check="handleDeptEditNodeCheck"
            show-checkbox node-key="id" ref="dept_tree2" :props="defaultProps" :default-expanded-keys="deptDefaule"
            :default-checked-keys="deptDefaule" :check-strictly="true" class="myDialogTree">
          </el-tree>
        </el-form-item>
        <el-form-item label="可查看部门" prop="VisitDeptIds" >
          <el-tree style="max-height:200px;overflow-y: auto;" :data="deptData" show-checkbox node-key="id"
            ref="dept_edit_tree" :props="defaultProps" :default-expanded-keys="viewDeptDefaule"
            :default-checked-keys="viewDeptDefaule" :check-strictly="true" class="myDialogTree">
          </el-tree>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input type="text" v-model="editForm.phone" autocomplete="off" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="editForm.email" autocomplete="off" placeholder="请输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="editDisabled" @click="editSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="角色分配" :visible.sync="centerDialogRole" width="40%" center custom-class="center_dislog" :before-close="centerDialogClose">
      <!-- 角色 -->
      <el-form :model="roleForm" label-width="80px">
        <el-form-item label="角色">
          <el-tree :data="roleForm.role_list" :props="roleDefaultProps" @check-change="handleNodeRoleChange"
            show-checkbox ref="role_tree" node-key="id" class="myDialogTree">
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogClose">取 消</el-button>
        <el-button type="primary" :disabled="roleDisabled" @click="updateRole">确 定</el-button>
      </span>
    </el-dialog>
  </el-main>
</template>
<script>
  import {
    mapState
  } from 'vuex'
  import {
    adminList,
    adminAdd,
    adminEdit,
    adminDelete,
    adminResetPwd,
    adminRole,
    deptList,
    roleList,
    adminfreeze,
    adminunfreeze
  } from '../../api.js'
  export default {
    name: "systemNumberAdmin",
    data() {
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.addForm.password) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      }
      var checkPhone = (rule, value, callback) => {
        if (value && (!(/^[1][3456789]\d{9}$/).test(value) || !(/^[1-9]\d*$/).test(value) || value.length !== 11)) {
          callback(new Error('请输入正确的手机号'))
        } else if (value == '') {
          callback(new Error('请输入手机号'))
        } else {
          callback()
        }
      };
      var checkEmail = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入邮箱'));
        } else {
          callback();
        }
      };
      return {
        addDialogVisible: false,
        editDialogVisible: false,
        centerDialogRole: false,
        breadcrumbName: '',
        breadcrumbPath: '',
        breadcrumbNameP: '',
        tableData: [],
        checkStrictly: true,
        rules: {
          password2: [{
            validator: validatePass2,
            trigger: 'blur'
          }],
          phone: [{
            validator: checkPhone,
            trigger: 'blur'
          }],
          email: [{
            validator: checkEmail,
            trigger: 'blur'
          }],
        },
        carrier_list: [],
        addForm: {
          UserName:'',
          password:'',
          password2:'',
          phone:'',
          email:'',
          audit:1,
          PermLevel:'',
          PlaceDeptId:'',//所在部门
          VisitDeptIds:'', //可查看部门
          nickName:''
        },
        editForm: {
          Uid:'',//用户id
          UserName:'',
          phone:'',
          email:'',
          audit:1,
          PermLevel:'',
          PlaceDeptId:'',
          nickName:'',
        },
        roleForm: {
          AdminId:'',
          RoleIds:'',
          role_id_arr: [],
          role_list: [],
        },
        roleDefaultProps: {
          children: 'children',
          label: 'name'
        },
        carrier_name: '',
        carrier_id: '',
        //分页
        total: 0,
        //查询栏默认展示数据
        formInline: {
          DeptId: 0,
          UserName: '',
          StartDt:'',
          EndDt:'',
          //时间范围选择器的值,
          dataValue: [],
          page: 1,
          limit: 5
        },
        allDeptData: [
        ],
        deptData: [],
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        num: 0,
        viewDeptDefaule: [],
        deptDefaule: [],
        addDisabled: false,
        editDisabled: false,
        roleDisabled: false,
      }
    },
    mounted() {
      this.breadcrumbName = this.$route.query.breadcrumbName
      this.breadcrumbPath = this.$route.query.breadcrumbPath
      this.breadcrumbNameP = this.$route.query.breadcrumbNameP

      this.getTableDate(this.formInline);
      this.getAllDeptList();
      this.getRoleList();
      // this.getCarrierList();
    },
    methods: {
      //获取表格数据
      getTableDate(searchObj) {
        var _this = this;
        var data={
          user_name:searchObj.UserName,
          start_date:searchObj.StartDt,
          end_date:searchObj.EndDt,
          dept_id:searchObj.DeptId,
          page: searchObj.page,
          limit: searchObj.limit
        }
         adminList(data).then(res => {
          if (res.ErrorCode == 0) {
              _this.tableData = res.Data.list
              _this.total = res.Data.total
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
      },
      handleSelect(val) {
        this.carrier_id = val.carrier_id
      },
      //獲取所有部門
      getAllDeptList() {
        var _this = this;
        deptList().then(res => {
          if (res.ErrorCode == 0) {
              _this.deptData = res.Data
              _this.allDeptData = [{
                children: [],
                id: 0,
                title: '全部部门'
              }]
              _this.allDeptData[0].children = res.Data
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
      },
      //获取角色列表
      getRoleList() {
        var _this = this;
         roleList().then(res => {
          if (res.ErrorCode == 0) {
           _this.roleForm.role_list = res.Data
          } else {
            this.$message.error(res.ErrorMsg);
          }
        })
      },
      //表格分页
      handleSizeChange(val) {
        console.log(`每頁 ${val} 條`);
      },
      handleCurrentChange(val) {
        this.formInline.page = val;
        this.getTableDate(this.formInline)
      },
      //表格查询
      onSearch() {
        this.formInline.page = 1;
        this.getTableDate(this.formInline)
      },
      //添加
      handleAdd() {
        this.getAllDeptList();
        // this.getCarrierList();
        this.addDialogVisible = true;
        // for(var k in this.addForm){
        //     this.addForm[k] = ''
        // }
        // this.addForm.isBanCarrier = false;
        // this.addForm.type = 0;
      },
      addSubmit() {
        this.addDisabled = true
        var _this = this;
        var dept_ids = []
        _this.$refs.dept_add_tree.getCheckedNodes().forEach(function (item) {
          dept_ids.push(item.id)
        })
        _this.addForm["VisitDeptIds"] = dept_ids.join(',')
        var dataAdd={
          user_name:_this.addForm.UserName,
          perm_level:_this.addForm.PermLevel,
          dept_id:_this.addForm.PlaceDeptId,
          dept_ids:_this.addForm.VisitDeptIds,
          phone:_this.addForm.phone,
          email:_this.addForm.email,
          password:_this.addForm.password,
          confirm_password:_this.addForm.password2,
        }
        adminAdd(dataAdd).then(res => {
        if (res.ErrorCode == 0) {
            _this.addDisabled = false
            _this.addDialogVisible = false;
            _this.$message.success("添加成功");
            _this.getTableDate(_this.formInline);
        } else {
          _this.addDisabled = false
          this.$message.error(res.ErrorMsg);
        }
      })
      },
      //表格的操作
      //编辑
      handleEdit(index, row) {
        var _this = this
        this.editDialogVisible = true
        this.editForm.Uid = row.id
        this.editForm.email = row.email
        this.editForm.phone = row.phone
        this.editForm.UserName = row.user_name
        this.editForm.nickName = row.nike_name
        this.editForm.PlaceDeptId = row.dept_id
        this.editForm.VisitDeptIds = row.dept_ids
        setTimeout(function () {
          _this.$refs.dept_tree2.setCheckedKeys([row.dept_id])
          _this.$refs.dept_edit_tree.setCheckedKeys(row.dept_ids)
          _this.deptDefaule = [row.dept_id]
          _this.viewDeptDefaule = row.dept_ids
        }, 50)
      },
      editSubmit() {
        this.editDisabled = true
        var _this = this;
        var dataObj = this.editForm
        var dept_ids = []
        _this.$refs.dept_edit_tree.getCheckedNodes().forEach(function (item) {
          dept_ids.push(item.id)
        })
        dataObj["VisitDeptIds"] = dept_ids.join(',')
        var dataAdd={
          id:dataObj.Uid,
          user_name:dataObj.UserName,
          perm_level:dataObj.PermLevel,
          dept_id:dataObj.PlaceDeptId,
          dept_ids:dataObj.VisitDeptIds,
          phone:dataObj.phone,
          email:dataObj.email,
        }
        adminEdit(dataAdd).then(res => {
          if (res.ErrorCode == 0) {
              _this.editDisabled = false;
              _this.editDialogVisible = false;
              _this.$message.success("编辑成功");
              _this.getTableDate(_this.formInline);
          } else {
           _this.editDisabled = false;
            this.$message.error(res.ErrorMsg);
          }
      })
      },
      //角色分配
      handleRole(index, row) {
        var _this = this;
        _this.roleForm.AdminId = row.id
        _this.roleForm.role_id_arr = []
        _this.centerDialogRole = true;
        _this.roleForm.role_id_arr.push(row.role_id)
        _this.roleForm.RoleIds = row.role_id
       setTimeout(function () {
          _this.$refs.role_tree.setCheckedKeys([row.role_id]);
        }, 50)
      },
      updateRole() {
        this.roleDisabled = true
        var _this = this;
        var data =  {
          id: _this.roleForm.AdminId,
          role_id: _this.roleForm.RoleIds,
        }
        adminRole(data).then(res => {
          if (res.ErrorCode == 0) {
              _this.roleDisabled = false;
              _this.centerDialogRole = false;
              _this.$refs.role_tree.setCheckedKeys([])
              _this.$message.success("分配成功");
              _this.getTableDate(_this.formInline);
          } else {
            _this.roleDisabled = false;
            this.$message.error(res.ErrorMsg);
          }
        })
      },
      //删除
      handleDe(row,tip,title){
        var _this = this
         var data = {
          id: row.id,
        }
         _this.$confirm(tip, title, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true
        }).then(() => {
          adminDelete(data).then(res => {
            if (res.ErrorCode == 0) {
                _this.getTableDate(_this.formInline);
                _this.$message.success("删除成功");
            } else {
              this.$message.error(res.ErrorMsg);
            }
          })
        }).catch(() => {
        });
      },
      //解冻，冻结
      handleDeStatus(row,status,tip,title){
        var _this = this
         var data = {
          id: row.id,
        }
         _this.$confirm(tip, title, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true
        }).then(() => {
          if(status == 1){
            data.do = "unfreeze"
            adminunfreeze(data).then(res => {
              if (res.ErrorCode == 0) {
                  _this.getTableDate(_this.formInline);
                  _this.$message.success("操作成功");
              } else {
                this.$message.error(res.ErrorMsg);
              }
            })
          }else{
            data.do = "freeze"
            adminfreeze(data).then(res => {
              if (res.ErrorCode == 0) {
                  _this.getTableDate(_this.formInline);
                  _this.$message.success("操作成功");
              } else {
                this.$message.error(res.ErrorMsg);
              }
            })
          }
        }).catch(() => {
        });
      },
      //删除
      handleDelete(index, row, status, tip, title) {
        if (status == 1) {
          this.handleDeStatus(row,status,tip,title)
        } else if (status == 2) {
          this.handleDeStatus(row,status,tip,title)
        } else if (status == 3) {
          this.handleDe(row,tip,title)
        }
      },
      handleReset(index, row) {
        var _this = this
        _this.$confirm('此操作將重置密码为11111111, 是否继续？', '重置密码', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          center: true
        }).then(() => {
          var data={
            id:row.id,
          }
          adminResetPwd(data).then(res => {
            if (res.ErrorCode == 0) {
              _this.$message.success("已重置");
              _this.getTableDate(_this.formInline);
            } else {
              this.$message.error(res.ErrorMsg);
            }
          })
        }).catch(() => {

        });
      },
      //表格数据处理
      formatAuidt(row, column, cellValue) {
        // 1=通过  -1=不通过 0= 待审核
        if (cellValue == 0) {
          return this.language.table_td_account_type2
        } else if (cellValue == 1) {
          return this.language.search_label_audit_yes
        } else {
          return this.language.search_label_audit_no
        }
      },
      // formatType(row, column, cellValue) {
      //   return cellValue == 0 ? '后台用户' : '承运商'
      // },
      formatStatu(row, column, cellValue) {
        return cellValue == 1 ? '启用' : '冻结'
      },
      formatDeptName(row, column, cellValue) {
        return Array.prototype.join.call(cellValue, '，');
      },
      //部门联动表格
      handleNodeClick(node) {
        console.log(node)
        this.formInline.DeptId = node.id;
        this.getTableDate(this.formInline)
      },
      handleNodeRoleChange(node, checked, indeterminate) {
        if (checked) {
          this.$refs.role_tree.setCheckedKeys([node.id])
          this.roleForm.RoleIds = node.id
        }
      },
      //部门单选
      handleDeptAddNodeCheck(data, checked, indeterminate) {
        if (checked.checkedKeys != []) {
          this.$refs.dept_tree.setCheckedKeys([data.id])
          this.addForm["PlaceDeptId"] = data.id
        }
      },
      handleDeptEditNodeCheck(data, checked, indeterminate) {
        if (checked.checkedKeys != []) {
          this.$refs.dept_tree2.setCheckedKeys([data.id])
          this.editForm["PlaceDeptId"] = data.id
        }
      },
      centerDialogClose(){
        this.centerDialogRole = false
        this.$refs.role_tree.setCheckedKeys([])
      },
      //角色下拉框change
      currentSel(selVal) {
        if (selVal == 2) {
          this.addForm.isBanCarrier = true
        } else {
          this.addForm.isBanCarrier = false
        }
      },
      switchChange(type) {
        if (type == 0) {
          this.editForm["isBanCarrierEdit"] = false
          this.editForm.carrier_id = ''
        } else {
          this.editForm["isBanCarrierEdit"] = true
        }
      },
      changeDatePicker(val) {
        if (val) {
          this.formInline.StartDt = val[0]
          this.formInline.EndDt = val[1]
        } else {
          this.formInline.StartDt = ''
          this.formInline.EndDt = ''
        }
      },
      closeForm(close) {
        if (close) {
          this.addDialogVisible = false
        }
        this.$refs.addForm.resetFields()
      },
      formatDept(row, column, cellValue){
        return Array.prototype.join.call(cellValue, '，');
      },
    },
    computed: {
      ...mapState({
        access_token: state => state.access_token,
        baseUrl: state => state.baseUrl,
      }),
    },
  }
</script>
<style scoped>
  .myTree {
    margin-top: 30px;
  }

  main>>>.el-autocomplete {
    width: 100%;
  }
  .buttomSty .el-button{
    margin: 5px 0;
    color: #333;
  }
</style>